<template>
  <div class="checkin-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>入住管理</span>
          <div>
            <el-button type="primary" @click="handleWalkIn">Walk-in入住</el-button>
            <el-button type="success" @click="showReservations = true">预订入住</el-button>
          </div>
        </div>
      </template>
      
      <!-- 状态筛选 -->
      <el-radio-group v-model="statusFilter" @change="loadData" style="margin-bottom: 20px">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="CHECKED_IN">在住</el-radio-button>
        <el-radio-button label="CHECKED_OUT">已退房</el-radio-button>
      </el-radio-group>
      
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="roomNumber" label="房间号" width="100" />
        <el-table-column prop="roomTypeName" label="房型" />
        <el-table-column prop="customerName" label="客户姓名" />
        <el-table-column prop="customerPhone" label="手机号" />
        <el-table-column label="入住时间">
          <template #default="{ row }">
            {{ formatDateTime(row.checkInTime) }}
          </template>
        </el-table-column>
        <el-table-column label="预计退房">
          <template #default="{ row }">
            {{ formatDate(row.expectedCheckOutTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="roomRate" label="房费(元/晚)" width="100" />
        <el-table-column prop="deposit" label="押金(元)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'CHECKED_IN' ? 'success' : 'info'">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button v-if="row.status === 'CHECKED_IN'" type="danger" size="small" @click="handleCheckOut(row)">退房</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadData"
        @current-change="loadData"
      />
    </el-card>
    
    <!-- Walk-in入住对话框 -->
    <el-dialog v-model="walkInDialogVisible" title="Walk-in入住" width="700px">
      <el-form ref="walkInFormRef" :model="walkInForm" :rules="walkInRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="walkInForm.customerName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="customerPhone">
              <el-input v-model="walkInForm.customerPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件类型" prop="customerIdType">
              <el-select v-model="walkInForm.customerIdType">
                <el-option label="身份证" value="ID_CARD" />
                <el-option label="护照" value="PASSPORT" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="customerIdNumber">
              <el-input v-model="walkInForm.customerIdNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间" prop="roomId">
              <el-select v-model="walkInForm.roomId" placeholder="请选择房间">
                <el-option
                  v-for="room in availableRooms"
                  :key="room.id"
                  :label="`${room.roomNumber} - ${room.typeName} (¥${room.price})`"
                  :value="room.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退房日期" prop="expectedCheckOutTime">
              <el-date-picker
                v-model="walkInForm.expectedCheckOutTime"
                type="datetime"
                placeholder="选择退房时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房费" prop="roomRate">
              <el-input v-model="walkInForm.roomRate">
                <template #append>元/晚</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押金" prop="deposit">
              <el-input v-model="walkInForm.deposit">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="notes">
          <el-input v-model="walkInForm.notes" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="walkInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleWalkInSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 预订列表对话框 -->
    <el-dialog v-model="showReservations" title="选择预订" width="900px">
      <el-table :data="todayReservations" v-loading="reservationsLoading">
        <el-table-column prop="reservationNo" label="预订号" />
        <el-table-column prop="customerName" label="客户姓名" />
        <el-table-column prop="customerPhone" label="手机号" />
        <el-table-column prop="roomNumber" label="房间号" />
        <el-table-column prop="roomTypeName" label="房型" />
        <el-table-column label="入住日期">
          <template #default="{ row }">
            {{ formatDate(row.checkInDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleCheckInReservation(row)">办理入住</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    
    <!-- 退房对话框 -->
    <el-dialog v-model="checkOutDialogVisible" title="办理退房" width="500px">
      <el-form :model="checkOutForm" label-width="100px">
        <el-form-item label="房间号">
          <el-input :value="checkOutForm.roomNumber" readonly />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input :value="checkOutForm.customerName" readonly />
        </el-form-item>
        <el-form-item label="总消费" prop="totalAmount">
          <el-input v-model="checkOutForm.totalAmount">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkOutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCheckOutSubmit">确认退房</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  getCheckInList,
  checkInWithReservation,
  checkInWithoutReservation,
  checkOut
} from '@/api/checkin'
import { getTodayCheckIns } from '@/api/reservation'
import { getRoomsByStatus } from '@/api/room'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')
const availableRooms = ref([])

// Walk-in入住
const walkInDialogVisible = ref(false)
const walkInFormRef = ref<FormInstance>()
const walkInForm = reactive({
  customerName: '',
  customerPhone: '',
  customerIdType: 'ID_CARD',
  customerIdNumber: '',
  roomId: null,
  expectedCheckOutTime: null,
  roomRate: '',
  deposit: '',
  notes: ''
})

const walkInRules: FormRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  customerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  customerIdNumber: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ],
  roomId: [
    { required: true, message: '请选择房间', trigger: 'change' }
  ],
  expectedCheckOutTime: [
    { required: true, message: '请选择退房时间', trigger: 'change' }
  ],
  roomRate: [
    { required: true, message: '请输入房费', trigger: 'blur' }
  ]
}

// 预订入住
const showReservations = ref(false)
const reservationsLoading = ref(false)
const todayReservations = ref([])

// 退房
const checkOutDialogVisible = ref(false)
const checkOutForm = reactive({
  id: null,
  roomNumber: '',
  customerName: '',
  totalAmount: ''
})

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getCheckInList({
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    let list = res.data.list
    
    // 按状态筛选
    if (statusFilter.value) {
      list = list.filter((item: any) => item.status === statusFilter.value)
    }
    
    tableData.value = list
    total.value = res.data.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadAvailableRooms = async () => {
  try {
    const res = await getRoomsByStatus('AVAILABLE')
    availableRooms.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const loadTodayReservations = async () => {
  reservationsLoading.value = true
  try {
    const res = await getTodayCheckIns()
    todayReservations.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    reservationsLoading.value = false
  }
}

const handleWalkIn = () => {
  Object.assign(walkInForm, {
    customerName: '',
    customerPhone: '',
    customerIdType: 'ID_CARD',
    customerIdNumber: '',
    roomId: null,
    expectedCheckOutTime: null,
    roomRate: '',
    deposit: '',
    notes: ''
  })
  walkInDialogVisible.value = true
}

const handleWalkInSubmit = async () => {
  if (!walkInFormRef.value) return
  
  await walkInFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await checkInWithoutReservation(walkInForm)
        ElMessage.success('入住办理成功')
        walkInDialogVisible.value = false
        loadData()
        loadAvailableRooms()
      } catch (error) {
        console.error(error)
      }
    }
  })
}

const handleCheckInReservation = async (reservation: any) => {
  await ElMessageBox.confirm(
    `确定要为预订"${reservation.reservationNo}"办理入住吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  try {
    await checkInWithReservation(reservation.id)
    ElMessage.success('入住办理成功')
    showReservations.value = false
    loadData()
    loadAvailableRooms()
  } catch (error) {
    console.error(error)
  }
}

const handleCheckOut = (row: any) => {
  checkOutForm.id = row.id
  checkOutForm.roomNumber = row.roomNumber
  checkOutForm.customerName = row.customerName
  checkOutForm.totalAmount = row.roomRate
  checkOutDialogVisible.value = true
}

const handleCheckOutSubmit = async () => {
  try {
    await checkOut({
      id: checkOutForm.id!,
      totalAmount: parseFloat(checkOutForm.totalAmount)
    })
    ElMessage.success('退房成功')
    checkOutDialogVisible.value = false
    loadData()
    loadAvailableRooms()
  } catch (error) {
    console.error(error)
  }
}

const handleEdit = (row: any) => {
  ElMessage.info('编辑功能暂未实现')
}

onMounted(() => {
  loadData()
  loadAvailableRooms()
})

// 监听预订列表对话框
onMounted(() => {
  const unwatch = showReservations
  if (showReservations.value) {
    loadTodayReservations()
  }
})
</script>

<style scoped>
.checkin-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>